//
//  ScrollerView.swift
//  Scroller_swift
//
//  Created by CarlsonLee on 2020/4/22.
//  Copyright © 2020 CarlsonLee. All rights reserved.
//

import UIKit

let kScrollerViewCell = "kScrollerViewCellKey"

class ScrollerView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    //轮播的方向
    enum ScrDirection {
        case ver, hor
    }
    //轮播的类型
    enum ScrType {
        case image, text
    }
    
    var collection: UICollectionView?
    var datas = [String]()
    var timer: Timer?
    var interval: Double = 3.0
    var scale: Int = 1000
    var scaleJump: Bool = false
    var callBack: ((Int)->())?
    //默认图片,水平滚动
    var type: ScrType = .image
    var direction: ScrDirection = .hor
    //使用的cell
    var itemCla: String = "ScrollerViewItem"
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        initSubviews()
    }
    //可社会轮播的类型和方向
    init(frame: CGRect, type: ScrType, dir: ScrDirection) {
        super.init(frame: frame)
        self.direction = dir
        self.type = type
        initSubviews()
    }
    //
    private func initSubviews() {
        let layout = UICollectionViewFlowLayout()
        if direction == .ver {
            layout.minimumLineSpacing = 0
            layout.minimumInteritemSpacing = 0
            layout.sectionInset = UIEdgeInsets.zero
            layout.scrollDirection = .vertical
        }else{
            layout.minimumLineSpacing = 10
            layout.minimumInteritemSpacing = 0
            layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
            layout.scrollDirection = .horizontal
        }
        if type == .image {
            itemCla = getAPPName() + "." + "ScrollViewImageItem"
        }else{
            itemCla = getAPPName() + "." + "ScrollerViewTextItem"
        }
                
        self.collection = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        self.collection?.delegate = self
        self.collection?.dataSource = self
        self.collection?.isPagingEnabled = true
        self.collection?.backgroundColor = UIColor.clear
        self.collection?.showsHorizontalScrollIndicator = false
        self.collection?.showsVerticalScrollIndicator = false
        self.collection?.register(NSClassFromString(itemCla).self, forCellWithReuseIdentifier: kScrollerViewCell)
        self.addSubview(self.collection!)

        //默认自动滚动
        setAutoScroll(true)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.collection?.frame = self.bounds
        if !scaleJump {
            scaleJump = true
            var index = self.datas.count*scale/10
            setIndex(&index, false)
        }
    }
    func loadDatas(_ urls: [String]) {
        self.datas = urls
        self.collection?.reloadData()
    }
    
    //设置轮播间隔时间
    func setInterval(_ val: Double) {
        if val > 0 {
            interval = val
            closeTimer()
            startTimer()
        }
    }
    //轮播是否自动滚动
    func setAutoScroll(_ auto: Bool) {
        if auto {
            self.setInterval(3.0)
        }else{
            closeTimer()
        }
    }
    //定时器
    func startTimer() {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(timerResponse), userInfo: nil, repeats: true)
        }
    }
    func closeTimer() {
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
    @objc func timerResponse() {
        var index = 0
        if direction == .ver {
            index = Int((collection?.contentOffset.y)! / bounds.height)
        }else{
            index = Int((collection?.contentOffset.x)! / bounds.width)
        }
        index += 1
        setIndex(&index, true)
    }
    //滚动到第几个banner
    func setIndex(_ idx: inout Int, _ ani: Bool) {
        var animation = ani
        if idx >= self.datas.count*scale {
            idx = 0
            animation = false
        }
        var point: CGPoint = CGPoint.zero
        if direction == .ver {
            point = CGPoint(x: 0, y: CGFloat(idx)*bounds.height)
        }else{
            point = CGPoint(x: CGFloat(idx)*bounds.width, y: 0)
        }
        collection?.setContentOffset(point, animated: animation)
    }
    //代理
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var size = bounds.size
        size.width = bounds.size.width-10
        return size
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.datas.count*scale
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kScrollerViewCell, for: indexPath) as! ScrollerViewItem
        let idx = indexPath.row % self.datas.count
        cell.setData(self.datas[idx])
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if callBack != nil {
            callBack?(indexPath.row%3)
        }
    }
    
    //获取app名称
    private func getAPPName() -> String {
        let nameKey = "CFBundleName"
        let appName = Bundle.main.object(forInfoDictionaryKey: nameKey) as? String
        return appName!
    }
}
